package cat

import (
	"cat-collage-backend/internal/model"
	"github.com/gin-gonic/gin"
	"github.com/google/uuid"
	"gorm.io/gorm"
	"net/http"
	"strconv"
)

type catResponse struct {
	Msg  string                `json:"msg"`
	Data []catResponseDataItem `json:"data"`
}

type catResponseDataItem struct {
	Cat       model.Cat           `json:"cat"`
	CatHobbys []model.CatHobby    `json:"catHobbys"`
	CatImages []model.CatImage    `json:"catImages"`
	CatPos    []model.CatPosition `json:"catPos"`
}

func UpdateCats(c *gin.Context, db *gorm.DB) {
	cat := &model.Cat{}
	err := c.ShouldBindJSON(cat)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	result := db.Where("id = ?", cat.ID).First(&model.Cat{})
	if result.Error != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Please provide correct catId"})
		return
	}
	result = db.Where("id = ?", cat.OwnerId).First(&model.User{})
	if result.Error != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Please provide correct ownerId"})
		return
	}
	result = db.Where("id = ?", cat.ID).Updates(cat)
	if result.Error != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Server error"})
		return
	}
	c.JSON(http.StatusOK, gin.H{"msg": "success", "data": nil})
}

func DeleteCats(c *gin.Context, db *gorm.DB) {
	catId, _ := c.GetPostForm("catId")
	if catId == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Please provide catId"})
		return
	}
	cat := &model.Cat{}
	// 删除 cat 表信息
	result := db.Where("id = ?", catId).Delete(&cat)
	if result.Error != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Server error"})
		return
	}
	// 删除 cat_hobby 表关联信息
	result = db.Where("cat_id = ?", catId).Delete(&model.CatHobby{})
	if result.Error != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Server error"})
		return
	}
	// 删除 cat_image 表关联信息
	result = db.Where("cat_id = ?", catId).Delete(&model.CatImage{})
	if result.Error != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Server error"})
		return
	}
	// 删除 cat_position 表关联信息
	result = db.Where("cat_id = ?", catId).Delete(&model.CatPosition{})
	if result.Error != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Server error"})
		return
	}
	if result.Error != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Server error"})
		return
	}
	c.JSON(http.StatusOK, gin.H{"msg": "删除成功", "data": nil})
}

func AddCats(c *gin.Context, db *gorm.DB) {
	cat := &model.Cat{}
	if id, err := uuid.NewRandom(); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Server error"})
		return
	} else {
		cat.ID = id.String()
	}
	err := c.ShouldBindJSON(cat)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	result := db.Where("id = ?", cat.OwnerId).First(&model.User{})
	if result.Error != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Please provide correct ownerId"})
		return
	}
	result = db.Create(cat)
	if result.Error != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Server error"})
	}
	c.JSON(http.StatusOK, gin.H{"msg": "success", "data": nil})
}

func GetCatsByOwner(c *gin.Context, db *gorm.DB) {
	ownerId := c.Param("ownerId")

	if ownerId == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Please provide ownerId"})
		return
	}
	limitStr := c.DefaultQuery("limit", "10")
	pageStr := c.DefaultQuery("page", "1")

	limit, err := strconv.Atoi(limitStr)
	if err != nil || limit <= 0 {
		limit = 10
	}

	page, err := strconv.Atoi(pageStr)
	if err != nil || page <= 0 {
		page = 1
	}
	offset := (page - 1) * limit
	cats := make([]model.Cat, 0)
	catHobbys := make([]model.CatHobby, 0)
	catImages := make([]model.CatImage, 0)
	catPos := make([]model.CatPosition, 0)

	db.Where("owner_id = ?", ownerId).Limit(limit).Offset(offset).Find(&cats)
	if len(cats) == 0 {
		c.JSON(200, gin.H{"error": "Cat not found", "data": nil})
		return
	}
	catIds := make([]string, len(cats))
	for i, cat := range cats {
		catIds[i] = cat.ID
	}
	db.Where("cat_id IN ?", catIds).Find(&catHobbys)
	db.Where("cat_id IN ?", catIds).Find(&catImages)
	db.Where("cat_id IN ?", catIds).Find(&catPos)
	r := catResponse{}
	for _, cat := range cats {
		item := catResponseDataItem{
			Cat:       cat,
			CatHobbys: make([]model.CatHobby, 0),
			CatImages: make([]model.CatImage, 0),
			CatPos:    make([]model.CatPosition, 0),
		}
		for _, catHobby := range catHobbys {
			if catHobby.CatId == item.Cat.ID {
				item.CatHobbys = append(item.CatHobbys, catHobby)
			}
		}
		for _, catImage := range catImages {
			if catImage.CatId == item.Cat.ID {
				item.CatImages = append(item.CatImages, catImage)
			}
		}
		for _, catPo := range catPos {
			if catPo.CatId == item.Cat.ID {
				item.CatPos = append(item.CatPos, catPo)
			}
		}
		r.Data = append(r.Data, item)
	}
	c.JSON(200, gin.H{"msg": "success", "data": r})
}
